package com.wpen.demo.config;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wpen.demo.core.KernelParams;
import com.wpen.unit.utils.JsonUtil;

/**
 * 
 * 
 * @author Wang Peng
 * @date 2022-12-06
 */
@Configuration
public class AppStartedConfig implements ApplicationRunner {
	@Value("${wpen.application.sleep-time:5}")
	private int sleepTime;

	@SuppressWarnings("unchecked")
	@Override
	public void run(ApplicationArguments appArgs) throws Exception {
		KernelParams.kernelStarted = true;
		String[] args = appArgs.getSourceArgs();
		try {
			System.out.println(">>>>>>" + (new ObjectMapper().writeValueAsString(args)));

			String jsonArgs = args[0];
			System.out.println(">>" + jsonArgs);
			Map<String, Object> maps = new HashMap<>();
			maps = (Map<String, Object>) JsonUtil.toObject(jsonArgs, Map.class);
			if (maps != null && !maps.isEmpty()) {
				if (maps.containsKey("sleepTime")) {
					if (maps.get("sleepTime") instanceof String) {
						sleepTime = Integer.parseInt((String) maps.get("sleepTime"));
					} else if (maps.get("sleepTime") instanceof Integer) {
						sleepTime = (int) maps.get("sleepTime");
					}
				}
			}

			for (int i = 0; i < sleepTime; i++) {
				System.out.println(sleepTime - i);
				Thread.sleep(1000);
			}

			System.out.println("bye ... ");
			if (args.length > 0 && "1".equals(args[0])) {
				//
			} else if (args.length > 0 && "2".equals(args[0])) {
				throw new RuntimeException("Test Exception");
			}
			System.exit(0);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(2);
		}
	}

}
